package io.github.yotta.common.web.advice;

import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter;
import org.springframework.http.converter.json.GsonHttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.Collection;
import java.util.Collections;
import java.util.Objects;

/**
 * @author yotta
 * @date 2022/11/7 20:37
 */
@Order(Ordered.LOWEST_PRECEDENCE)
public abstract class BaseResponseAdvice implements ResponseBodyAdvice<Object> {

    @Setter
    @Autowired(required = false)
    private ResponseWrapper responseWrapper = new DefaultResponseWrapper();
    @Override
    public boolean supports(MethodParameter methodParameter, Class converterType) {
        return AbstractJackson2HttpMessageConverter.class.isAssignableFrom(converterType)
                || FastJsonHttpMessageConverter.class.isAssignableFrom(converterType)
                || GsonHttpMessageConverter.class.isAssignableFrom(converterType);
    }

    /**
     * 将请求控制器方法统一包装成一个类型
     *
     * @param body                  the body to be written 请求体，
     * @param returnType            控制器方法的包装类，可以拿到本次方法的返回值，对应的Method
     * @param selectedContentType   the content type selected through content negotiation
     * @param selectedConverterType the converter type selected to write to the response
     * @param request               the current request
     * @param response              the current response
     * @return the body that was passed in or a modified (possibly new) instance
     */
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType,
                                  MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  ServerHttpRequest request,
                                  ServerHttpResponse response) {
        // 获取当前请求对应的controller方法的返回值类型
        Class<?> rs = Objects.requireNonNull(returnType.getMethod()).getReturnType();
        if (responseWrapper != null) {
            return responseWrapper.wrapperResponse(body, rs);
        }
        return body;
    }

    private Object getDefaultValue(MethodParameter returnType) {
        return Collection.class.isAssignableFrom(Objects.requireNonNull(returnType.getMethod()).getReturnType()) ? Collections.EMPTY_LIST : null;
    }

}
